package com.km.wskj.itmonitor.pager.wq.forum;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.fingdo.statelayout.StateLayout;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.global.ClassifyParams;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.FuncItem;
import com.km.wskj.itmonitor.model.Imgs;
import com.km.wskj.itmonitor.model.KnowledgeLibrary;
import com.km.wskj.itmonitor.pager.base.LActivity;
import com.km.wskj.itmonitor.pager.login.LoginActivity;
import com.km.wskj.itmonitor.pager.wq.ClassifyActivity;
import com.km.wskj.itmonitor.pager.wq.forum.model.ForumCard;
import com.zxl.zxlapplibrary.adapter.BaseAdapterHelper;
import com.zxl.zxlapplibrary.global.Constant;
import com.zxl.zxlapplibrary.util.LogUtils;
import com.zxl.zxlapplibrary.view.MyGridView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import zrc.widget.SimpleFooter;
import zrc.widget.SimpleHeader;
import zrc.widget.ZrcListView;

/**
 * @author by Xianling.Zhou on 2017/3/30.
 */
//论坛主页
public class ForumActivity extends LActivity implements StateLayout.OnViewRefreshListener {
    private static final String TAG = "ForumActivity";
    //ui
    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right)
    ImageView toolBarRight;
    @BindView(R.id.zrcListView)
    ZrcListView mZrcListView;
    @BindView(R.id.state_layout)
    StateLayout stateLayout;

    private LinearLayout mContainer;
    private MyAdapter mAdapter;
    private int lastUpdateNum;
    private int pageIndex;
    private String id;
    private List<KnowledgeLibrary> mKnowledgeLibrarys;
    private String tel;
    private List<FuncItem> funcItems = new ArrayList<>();
    private MyGridView gridView;
    private List<ForumCard> mForumCards;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forum);
        ButterKnife.bind(this);
        toolBarTitle.setText("论坛");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRight.setVisibility(View.VISIBLE);
        toolBarRight.setImageResource(R.mipmap.search_white);

        stateLayout.setRefreshListener(this);

        initData();

    }

    private void initData() {
        stateLayout.showLoadingView();
        pdc.knowledgeLib(HTTP_TASK_TAG, null, new ZxlGenericsCallback<List<KnowledgeLibrary>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<KnowledgeLibrary> kls, int i) {
                mKnowledgeLibrarys = kls;
            }
        });

        pdc.forumList(HTTP_TASK_TAG, id, 1, Constant.PageListSize, null, new ZxlGenericsCallback<List<ForumCard>>() {
            @Override
            public void onError(Call call, Exception e, int i) {
                LogUtils.e(TAG, e);
                mZrcListView.setRefreshFail("数据获取失败");
                stateLayout.showErrorView();
            }

            @Override
            public void onResponse(List<ForumCard> fcs, int i) {
                mForumCards = fcs;
                lastUpdateNum = fcs.size();
                pageIndex = 1;
                //control
                mAdapter.notifyDataSetChanged();
                mZrcListView.setRefreshSuccess();

                if (haveMore())
                    mZrcListView.startLoadMore();
                else
                    mZrcListView.stopLoadMore();
            }
        });

        initPullToRefresh();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                onRefresh();
                break;
            default:
                break;
        }
    }

    private void initPullToRefresh() {
        //添加头布局
        View view = getLayoutInflater().inflate(R.layout.header_forum, null);
        mContainer = (LinearLayout) view.findViewById(R.id.container);
        mContainer.removeAllViews();
        initFuncItems();

        mContainer.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                createGridView();
            }
        });
        if (mZrcListView.getHeaderViewsCount() == 0)
            mZrcListView.addHeaderView(view, null, true);//注意：第三个参数必须为true，否则无效

        //配置listview
        ColorDrawable line = new ColorDrawable(getResources().getColor(R.color.color_line2));
        mZrcListView.setDivider(line);
        mZrcListView.setDividerHeight(1);

        //设置下拉刷新的样式（可选，但如果没有Header则无法下拉刷新）
        SimpleHeader header = new SimpleHeader(context);
        header.setTextColor(ContextCompat.getColor(context, R.color.text_gray));
        header.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setHeadable(header);

        //设置加载更多的样式（可选）
        SimpleFooter footer = new SimpleFooter(context);
        footer.setCircleColor(ContextCompat.getColor(context, R.color.colorPrimary));
        mZrcListView.setFootable(footer);

        // 设置列表项出现动画（可选）
        //zListView.setItemAnimForTopIn(R.anim.topitem_in);
        mZrcListView.setItemAnimForBottomIn(R.anim.bottomitem_in);

        // 下拉刷新事件回调（可选）
        mZrcListView.setOnRefreshStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onRefresh();
            }
        });

        // 加载更多事件回调（可选）
        mZrcListView.setOnLoadMoreStartListener(new ZrcListView.OnStartListener() {
            @Override
            public void onStart() {
                onLoadMore();
            }
        });
        // 项目选中
        mZrcListView.setOnItemClickListener(new ZrcListView.OnItemClickListener() {
            @Override
            public void onItemClick(ZrcListView parent, View view, int position, long id) {
                ForumCard fc = (ForumCard) parent.getItemAtPosition(position);
                Intent t = new Intent(context, ForumDetailActivity.class);
                t.putExtra("data", fc);
                startActivity(t);
            }
        });

        mAdapter = new MyAdapter();
        mZrcListView.setAdapter(mAdapter);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                stateLayout.showContentView();
            }
        }, 500);
    }

    private void onRefresh() {
        pdc.forumList(HTTP_TASK_TAG, id, 1, Constant.PageListSize, null,
                new ZxlGenericsCallback<List<ForumCard>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                        mZrcListView.setRefreshFail("数据获取失败");
                        stateLayout.showErrorView();
                    }

                    @Override
                    public void onResponse(List<ForumCard> fcs, int i) {
                        mForumCards = fcs;
                        lastUpdateNum = fcs.size();
                        pageIndex = 1;
                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setRefreshSuccess();

                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });
    }

    private void onLoadMore() {
        pdc.forumList(HTTP_TASK_TAG, id, pageIndex + 1, Constant.PageListSize, null
                , new ZxlGenericsCallback<List<ForumCard>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                        mZrcListView.setRefreshFail("数据获取失败");
                    }

                    @Override
                    public void onResponse(List<ForumCard> fcs, int i) {
                        lastUpdateNum = fcs.size();
                        if (fcs.size() > 0) {
                            mForumCards.addAll(fcs);
                            pageIndex++;
                        }
                        //control
                        mAdapter.notifyDataSetChanged();
                        mZrcListView.setLoadMoreSuccess();
                        if (haveMore())
                            mZrcListView.startLoadMore();
                        else
                            mZrcListView.stopLoadMore();
                    }
                });
    }

    private boolean haveMore() {
        return lastUpdateNum > 0;
    }

    @OnClick({R.id.tool_bar_back, R.id.floatingActionButton, R.id.tool_bar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.floatingActionButton:
                if (pdc.mCurrentUser != null) {
                    Intent t = new Intent(context, ClassifyActivity.class);
                    t.putExtra("index", 1);//用来标示是分类、还是发表贴子，1代码发帖 2代表分类
                    startActivity(t);
                } else {
                    normalToasty("请先登录");
                    openIntent(LoginActivity.class, true);
                }
                break;
            case R.id.tool_bar_right:
                openIntent(ForumSearchListActivity.class, true);
                break;
        }
    }

    //点击重试
    @Override
    public void refreshClick() {
        initData();
    }

    @Override
    public void loginClick() {
    }

    /**
     * 适配器
     */
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            if (mForumCards == null) {
                return 0;
            }
            return mForumCards.size();
        }

        @Override
        public Object getItem(int position) {
            return mForumCards.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getViewTypeCount() {
            return 1;
        }

        @Override
        public int getItemViewType(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final BaseAdapterHelper helper = BaseAdapterHelper.get(context, convertView
                    , parent, R.layout.item_card_list);
            ForumCard item = mForumCards.get(position);
            helper.setText(R.id.tv_title, item.title + "");

            if (item.tel_no.length() == 11)
                tel = item.tel_no.substring(0, 3) + "****" + item.tel_no.substring(7);

            helper.setText(R.id.tv_author, item.nickname == null ? tel : item.nickname);
            helper.setText(R.id.tv_create_time, item.createTime + "");

            //设置头像
            if (item.head_img != null) {
                Glide.with(mActivity)
                        .load(item.host + item.head_img)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.header_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }

            //没有图片的时候才显示内容
            if (item.imgs.size() == 0 || item.imgs == null) {
                helper.setVisible(R.id.tv_content, true);
                helper.setText(R.id.tv_content, item.title + "");
                helper.setVisible(R.id.iv_one_img, false);//显示一张图片控件
                helper.setVisible(R.id.ll_three_img, false);//显示一张图片控件

            } else
                helper.setVisible(R.id.tv_content, false);

            //判断显示图片
            //一张图片
            if (item.imgs.size() > 0 && item.imgs.size() < 3) {

                helper.setVisible(R.id.iv_one_img, true);//显示一张图片控件
                helper.setVisible(R.id.tv_content, false);
                helper.setVisible(R.id.ll_three_img, false);

                Imgs imgs = item.imgs.get(0);
                Glide.with(mActivity)
                        .load(item.host + imgs.file_path + imgs.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_one_img, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
                //显示三张
            } else if (item.imgs.size() >= 3) {
                helper.setVisible(R.id.iv_one_img, false);
                helper.setVisible(R.id.tv_content, false);
                helper.setVisible(R.id.ll_three_img, true);

                Imgs imgs1 = item.imgs.get(0);
                Imgs imgs2 = item.imgs.get(1);
                Imgs imgs3 = item.imgs.get(2);

                Glide.with(mActivity)
                        .load(item.host + imgs1.file_path + imgs1.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {

                                helper.setImageBitmap(R.id.iv_img1, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(mActivity)
                        .load(item.host + imgs2.file_path + imgs2.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img2, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型

                Glide.with(mActivity)
                        .load(item.host + imgs3.file_path + imgs3.new_file_name)
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                helper.setImageBitmap(R.id.iv_img3, resource);
                            }

                            @Override
                            public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                super.onLoadFailed(e, errorDrawable);
                                LogUtils.e("LLpp:加载失败");
                            }
                        }); //方法中设置asBitmap可以设置回调类型
            }
            return helper.getView();
        }
    }

    private void initFuncItems() {
        String s[] = getResources().getStringArray(R.array.ws_college_func_title);
        int r[] = {R.mipmap.monitor_application
                , R.mipmap.monitor_database
                , R.mipmap.monitor_memory
                , R.mipmap.monitor_internet
                , R.mipmap.all
        };

        funcItems.clear();

        for (int i = 0; i < s.length && i < r.length; i++) {
            FuncItem fi = new FuncItem();
            fi.name = s[i];
            fi.resId = r[i];
            funcItems.add(fi);
        }
    }


    private void createGridView() {
        gridView = new MyGridView(context, new MyGridView.MyGridViewAdapter() {
            @Override
            public int rowspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colspacing(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int leftpadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int toppadding(MyGridView myGridView) {
                return 0;
            }

            @Override
            public int colCount(MyGridView myGridView) {
                return 5;
            }

            @Override
            public int rowHeight(MyGridView myGridView) {
                return mContainer.getHeight() / 1;
            }

            @Override
            public int viewWidth(MyGridView myGridView) {
                return mContainer.getWidth();
            }

            @Override
            public int count(MyGridView myGridView) {
                return funcItems.size();
            }

            @Override
            public View cell(int i, MyGridView myGridView) {
                View view = getLayoutInflater().inflate(R.layout.forum_item_func, null);
                ImageView iv_pic = (ImageView) view.findViewById(R.id.iv_pic);
                TextView tv_name = (TextView) view.findViewById(R.id.tv_name);

                FuncItem fi = funcItems.get(i);
                iv_pic.setImageResource(fi.resId);
                tv_name.setText(fi.name);


                return view;
            }

            @Override
            public View title(int i, MyGridView myGridView) {
                return null;
            }

            @Override
            public int titleOffsetY(MyGridView myGridView) {
                return 0;
            }

            @Override
            public boolean needGridLine(MyGridView myGridView) {
                return false;
            }
        });


        gridView.setListener(new MyGridView.MyGridViewListener() {
            @Override
            public void onCellTouchDown(int i) {

            }

            @Override
            public void onCellTouchUp(int i) {

            }

            @Override
            public void onCellLongPress(int i) {

            }

            @Override
            public void onCellClick(int i) {

                switch (i) {
                    //操作系统
                    case 0: {
                        KnowledgeLibrary item = getItem("操作系统");
                        Intent t = new Intent(context, ForumTabListActivity.class);
                        t.putExtra("data", item);
                        startActivity(t);
                    }
                    break;
                    //数据库
                    case 1: {
                        KnowledgeLibrary item = getItem("数据库");
                        Intent t = new Intent(context, ForumTabListActivity.class);
                        t.putExtra("data", item);
                        startActivity(t);

                    }
                    break;
                    //存储
                    case 2: {
                        KnowledgeLibrary item = getItem("存储");
                        Intent t = new Intent(context, ForumTabListActivity.class);
                        t.putExtra("data", item);
                        startActivity(t);
                    }
                    break;
                    //网络
                    case 3: {
                        KnowledgeLibrary item = getItem("网络");
                        Intent t = new Intent(context, ForumTabListActivity.class);
                        t.putExtra("data", item);
                        startActivity(t);
                    }
                    break;
                    //全部
                    case 4: {
                        Intent t = new Intent(context, ClassifyActivity.class);
                        t.putExtra("index", ClassifyParams.FORUM_ALL);
                        startActivity(t);
                    }
                }
            }
        });
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mContainer.addView(gridView.getView(), p);
    }

    //通过栏目名获取
    private KnowledgeLibrary getItem(String str) {
        for (KnowledgeLibrary kl : mKnowledgeLibrarys
                ) {
            if (str.equals(kl.columnName)) {
                return kl;
            }

        }
        return null;
    }


}
